package com.lw.leetcode.stack.b;

import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * 面试题 03.05. 栈排序
 *
 * @author liw
 * @version 1.0
 * @date 2021/9/9 17:49
 */
class SortedStack {

    private Stack<Integer> a;
    private Stack<Integer> b;

    public SortedStack() {
        a = new Stack<>();
        b = new Stack<>();
    }

    public void push(int val) {
        while (!b.isEmpty() && b.peek() > val) {
            a.add(b.pop());
        }

        while (!a.isEmpty() && a.peek() < val ) {
            b.add(a.pop());
        }
        a.add(val);
    }

    public void pop() {
        while (!b.isEmpty()) {
            a.add(b.pop());
        }
        if (!a.isEmpty()) {
            a.pop();
        }
    }

    public int peek() {
        while (!b.isEmpty()) {
            a.add(b.pop());
        }
        return a.isEmpty() ? -1 : a.peek();
    }

    public boolean isEmpty() {
        return a.isEmpty();
    }

}
